﻿namespace com.vs.General
{
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Reflection;
    using System.Security.Policy;
    using System.Text;

    public class FileManager
    {
        public static string _viewerFileExtension = ".XML";
        public const string CLIENT_DIRECTORY = "Client";
        public static Encoding DEFAULTENCODING = Encoding.UTF8;
        public static string RESOURCEIMAGES = "ResourceImages";
        public static string UserCfgFileExtension = ".config";

        public static string AddBackSlash(string path)
        {
            return ((StringManager.IsEmpty(path) || path.EndsWith(@"\")) ? path : (path + @"\"));
        }

        public static void Append(string file, string data)
        {
            OperateOnFile(file, null, AccessType.Append, data, null, false);
        }

        public static void Append(string file, string data, Encoding encFormat)
        {
            OperateOnFile(file, null, AccessType.Append, data, encFormat, false);
        }

        public static string ConvertToCommaSeparatedValues(Session session, DataTable table)
        {
            StringBuilder builder = new StringBuilder();
            int count = table.Columns.Count;
            int num2 = 0;
            while (num2 < count)
            {
                builder.Append(MaskCommaSeparatedValue(table.Columns[num2].ColumnName));
                if (num2 < count)
                {
                    builder.Append(",");
                }
                num2++;
            }
            foreach (DataRow row in table.Rows)
            {
                builder.Append("\r\n");
                for (num2 = 0; num2 < count; num2++)
                {
                    if (num2 < count)
                    {
                        builder.Append(",");
                    }
                }
            }
            return builder.ToString();
        }

        public static void CreateDirectory(string directoryName)
        {
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
        }

        public static void Delete(string file)
        {
            OperateOnFile(file, null, AccessType.Delete, null, null, false);
        }

        public static bool DirectoryExists(string dir)
        {
            return Directory.Exists(dir);
        }

        public static bool Exists(string file)
        {
            return File.Exists(file);
        }

        public static string GetAppConfigFilename()
        {
            return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
        }

        public static string GetAppDirectory()
        {
            try
            {
                return null;
            }
            finally
            {
            }
        }

        public static string GetAssemblyDirectory()
        {
            try
            {
                return AddBackSlash(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            }
            finally
            {
            }
        }

        public static FileAttributes GetAttributes(string fileName)
        {
            if (File.Exists(fileName))
            {
                return File.GetAttributes(fileName);
            }
            return File.GetAttributes("");
        }

        public static string GetCultureDirectory(CultureInfo culture)
        {
            string path = null;
            string str2;
            try
            {
                path = GetAppDirectory() + culture.Name;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                str2 = path;
            }
            finally
            {
                path = null;
            }
            return str2;
        }

        public static FileInfo[] GetDirectoryFiles(string dir)
        {
            FileInfo[] files = null;
            DirectoryInfo info = new DirectoryInfo(dir);
            if (info.Exists)
            {
                files = info.GetFiles();
            }
            return files;
        }

        public static string GetDirectoryFromPath(string fullPath)
        {
            return fullPath.Replace(Path.GetFileName(fullPath), "");
        }

        public static string[] GetFiles(string dir, string ext)
        {
            string[] strArray = null;
            if (StringManager.IsEmpty(dir) || !Directory.Exists(dir))
            {
                return strArray;
            }
            if (StringManager.IsEmpty(ext))
            {
                ext = "*";
            }
            if (ext.IndexOf("*.") > -1)
            {
                return Directory.GetFiles(dir, ext);
            }
            return Directory.GetFiles(dir, "*." + ext);
        }

        public static string[] GetFilesBySearchPattern(string dir, string pattern)
        {
            if (!StringManager.IsEmpty(dir) && Directory.Exists(dir))
            {
                if (StringManager.IsEmpty(pattern))
                {
                    pattern = "*";
                }
                return Directory.GetFiles(dir, pattern);
            }
            return null;
        }

        public static string GetImageDirectory()
        {
            return AddBackSlash(GetAppDirectory() + RESOURCEIMAGES);
        }

        public static Stream GetIsolatedStream(string user)
        {
            return new IsolatedStorageFileStream(GetUserConfigFileName(user), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User, typeof(StrongName), typeof(StrongName)));
        }

        public static Stream GetIsolatedStream(string filename, FileMode mode)
        {
            string[] strArray = null;
            IsolatedStorageFile isf = null;
            strArray = new string[1];
            isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User, typeof(StrongName), typeof(StrongName));
            if ((isf.GetFileNames(filename).Length > 0) || mode.Equals(FileMode.OpenOrCreate))
            {
                return new IsolatedStorageFileStream(filename, mode, FileAccess.ReadWrite, FileShare.ReadWrite, isf);
            }
            return null;
        }

        public static string GetServerDirectory()
        {
            try
            {
                return null;
            }
            finally
            {
            }
        }

        public static StreamWriter GetStreamWriter(string fileName)
        {
            return GetStreamWriter(fileName, Encoding.UTF8);
        }

        public static StreamWriter GetStreamWriter(string fileName, Encoding encoding)
        {
            return new StreamWriter(File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read), encoding);
        }

        public static string GetUserConfigFileName(string user)
        {
            return (user + UserCfgFileExtension);
        }

        public static string GetValidFileName(string filename)
        {
            foreach (char ch in InvalidPathChars)
            {
                filename = filename.Replace(ch.ToString(), "");
            }
            return filename;
        }

        public static Assembly LoadAssembly(string file)
        {
            return (Assembly) OperateOnFile(file, null, AccessType.LoadAssembly, null, null, false);
        }

        private static string MaskCommaSeparatedValue(string rawValue)
        {
            if (!StringManager.IsEmpty(rawValue) && (rawValue.IndexOf(",") >= 0))
            {
                if (rawValue.IndexOf("\"") >= 0)
                {
                    rawValue = StringManager.ReplaceAll(rawValue, "\"", "\"\"");
                }
                rawValue = "\"" + rawValue + "\"";
            }
            return rawValue;
        }

        public static void Move(string sourceFile, string destFile)
        {
            Rename(sourceFile, destFile, null);
        }

        public static string OpenFileInApp(string filePath)
        {
            try
            {
                Process.Start(filePath);
                return null;
            }
            catch (Win32Exception)
            {
                return "MSG_PMD01";
            }
        }

        private static object OperateOnFile(string file, string ext, AccessType type, string data, Encoding encFormat, bool overWrite)
        {
            ArrayList list = null;
            string str = null;
            StreamReader reader = null;
            StreamWriter writer = null;
            string path = null;
            string directoryFromPath = null;
            object obj2;
            try
            {
                if (!StringManager.IsEmpty(file))
                {
                    path = file;
                }
                else
                {
                    path = AddBackSlash("NoFileNamePassed") + Guid.NewGuid().ToString();
                }
                if (!StringManager.IsEmpty(ext))
                {
                    if (ext.StartsWith("."))
                    {
                        path = path + ext;
                    }
                    else
                    {
                        path = path + "." + ext;
                    }
                }
                switch (type)
                {
                    case AccessType.Append:
                        if (!StringManager.IsEmpty(data))
                        {
                            if (encFormat == null)
                            {
                                encFormat = DEFAULTENCODING;
                            }
                            new StreamWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.None), encFormat).Write(data);
                        }
                        return null;

                    case AccessType.Delete:
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        return null;

                    case AccessType.LoadAssembly:
                        if (!File.Exists(path))
                        {
                            return null;
                        }
                        return Assembly.LoadFrom(path);

                    case AccessType.Read:
                        if (!File.Exists(path))
                        {
                            return null;
                        }
                        if (encFormat == null)
                        {
                            encFormat = DEFAULTENCODING;
                        }
                        reader = new StreamReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None), encFormat);
                        if (reader.Peek() >= 0)
                        {
                            str = reader.ReadToEnd();
                        }
                        return str;

                    case AccessType.ReadLines:
                        if (!File.Exists(path))
                        {
                            return null;
                        }
                        if (encFormat == null)
                        {
                            encFormat = DEFAULTENCODING;
                        }
                        reader = new StreamReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None), encFormat);
                        list = new ArrayList();
                        while (reader.Peek() >= 0)
                        {
                            list.Add(reader.ReadLine().Trim());
                        }
                        return list;

                    case AccessType.Write:
                        if (!StringManager.IsEmpty(data))
                        {
                            if (overWrite || !File.Exists(path))
                            {
                                break;
                            }
                            OperateOnFile(path + Guid.NewGuid().ToString(), ext, AccessType.Write, data, encFormat, true);
                        }
                        return path;

                    default:
                        goto Label_02AD;
                }
                directoryFromPath = GetDirectoryFromPath(path);
                if (!Directory.Exists(directoryFromPath))
                {
                    Directory.CreateDirectory(directoryFromPath);
                }
                if (encFormat == null)
                {
                    encFormat = DEFAULTENCODING;
                }
                writer = new StreamWriter(File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None), encFormat);
                writer.Write(data);
                return path;
            Label_02AD:
                obj2 = null;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (writer != null)
                {
                    writer.Flush();
                    writer.Close();
                }
            }
            return obj2;
        }

        public static string Read(string file)
        {
            return (string) OperateOnFile(file, null, AccessType.Read, null, null, false);
        }

        public static string Read(string file, Encoding encFormat)
        {
            return (string) OperateOnFile(file, null, AccessType.Read, null, encFormat, false);
        }

        public static ArrayList ReadLines(string file)
        {
            return (ArrayList) OperateOnFile(file, null, AccessType.ReadLines, null, null, false);
        }

        public static ArrayList ReadLines(string file, Encoding encFormat)
        {
            return (ArrayList) OperateOnFile(file, null, AccessType.ReadLines, null, encFormat, false);
        }

        public static string Rename(string file, string newFile, string newFileExt)
        {
            string data = Read(file);
            Delete(file);
            return Write(newFile, newFileExt, data);
        }

        public static void SetAttributes(string fileName, FileAttributes fileNameAttributes)
        {
            if (File.Exists(fileName))
            {
                File.SetAttributes(fileName, fileNameAttributes);
            }
        }

        public static string[] SortByDate(string[] files)
        {
            if (files != null)
            {
                for (int i = files.Length - 1; i >= 0; i--)
                {
                    for (int j = 1; j <= i; j++)
                    {
                        if (File.GetLastWriteTime(files[j - 1]) > File.GetLastWriteTime(files[j]))
                        {
                            string str = files[j - 1];
                            files[j - 1] = files[j];
                            files[j] = str;
                        }
                    }
                }
            }
            return files;
        }

        public static string Write(string file, string ext, string data)
        {
            return Write(file, ext, data, null, false);
        }

        public static string Write(string file, string ext, string data, bool overwrite)
        {
            return Write(file, ext, data, null, overwrite);
        }

        public static string Write(string file, string ext, string data, Encoding encFormat)
        {
            return Write(file, ext, data, encFormat, false);
        }

        public static string Write(string file, string ext, string data, Encoding encFormat, bool overwrite)
        {
            return (string) OperateOnFile(file, ext, AccessType.Write, data, encFormat, overwrite);
        }

        public static char[] InvalidPathChars
        {
            get
            {
                return new char[] { '\\', '/', ':', '*', '?', '"', '<', '>', '|' };
            }
        }

        private enum AccessType
        {
            Append,
            Delete,
            LoadAssembly,
            Read,
            ReadLines,
            Write
        }
    }
}

